// index.js
// 获取应用实例
const app = getApp()
const DB = wx.cloud.database();
Page({
  data: {
    myOrder: {
      _id: "",
      version: 1
    },
    watcher: {}
  },
  // 事件处理函数
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  insert() {
    DB.collection("desk_order").add({
      data: {
        _id: "abc",
        version: 0
      },
      success(res) {
        console.log("添加成功", res);
      },
      fail(res) {
        console.log("失败啦", res);
      }
    });
  },
  update(version) {
    DB.collection("desk_order").doc(this.data.myOrder._id).update({
      data: {
        version: version
      },
      success(res) {
        console.log("修改成功", res);
      },
      fail(res) {
        console.log("修改失败啦", res);
      }
    })
  },
  loadAndWatch() {
    var thiz = this;
    thiz.initWatcher();
  },
  initWatcher() {
    console.log("正在连接...");
    var thiz = this;
    var watcher = this.data.watcher;
    if (watcher.close != null) {
      console.log("未关闭");
      // watcher.close();
    }
      watcher = DB.collection("desk_order").doc("abc").watch({
        onChange: function (snapshot) {
          console.log("收到消息", snapshot);
          var docs = snapshot.docs;
          if (docs.length == 0) {
            console.log("关闭连接");
            thiz.watcher.close();
            return;
          }
          thiz.setData({
            "myOrder": docs[0]
          });
        },
        onError: function (err) {
          console.log('watch error --->', err);
        }
      });
    
    console.log(watcher)
    thiz.setData({
      "watcher": watcher
    });
    return watcher;
  },
  myChange() {
    var version = new Date().getTime();
    this.update(version);
  },
  onLoad() {
    var thiz = this;
    this.loadAndWatch();
  }

})